package blog.gui;

import javax.microedition.lcdui.*;

import blog.*;
import blog.controller.*;
import blog.util.*;
import blog.db.*;

public class ConfigGui extends Form implements IBaseGui, CommandListener {
	
	private static Command cmdBack = new Command( ConstString.CMD_BACK, Command.BACK, 0 );
	private static Command cmdSave = new Command( ConstString.CMD_SAVE, Command.SCREEN, 0 );
	
	StringItem promptString;
	TextField numSize;
	
	boolean publishOk;

	public ConfigGui( boolean publishOk ) {
		super(ConstString.GUI_TITLE_CONFIG);
		
		promptString = new StringItem("", ConstString.GUI_CONFIG_PROMPT_STRING, Item.PLAIN );
		if ( publishOk )
		{
			numSize = new TextField(StringUtils.combin(ConstString.GUI_CONFIG_NUM_SIZE, "60"), String.valueOf(SysRuntime.curAccount.getLenHistoryList()), 2, TextField.NUMERIC);
		}
		else
		{
			numSize = new TextField(StringUtils.combin(ConstString.GUI_CONFIG_NUM_SIZE, "20"), String.valueOf(SysRuntime.curAccount.getLenEntryList()), 2, TextField.NUMERIC);
		}
		this.publishOk = publishOk;
		
		addCommand(cmdBack);
		addCommand(cmdSave);
		this.setCommandListener(this);
		this.append(promptString);
		append(numSize);
	}

	public int getIdentify() {
		return 0;
	}

	public void notifyChanged(Object param) {
		
	}

	public void commandAction(Command cmd, Displayable arg1) {
		if ( cmd==cmdBack )
		{
			SysRuntime.guiManager.back();
		}
		else if ( cmd==cmdSave )
		{
			if ( !checkOk() )
				return;
			int n = Integer.parseInt(numSize.getString());
			if ( publishOk )
			{
				SysRuntime.curAccount.setLenHistoryList( n );
				//BlogEntryDB.setMaxSize( SysRuntime.curAccount.getId(), n, true );
			}
			else
			{
				SysRuntime.curAccount.setLenEntryList( n );
				//BlogEntryDB.setMaxSize( SysRuntime.curAccount.getId(), n, false );
			}
			BlogAccountDB.update(SysRuntime.curAccount);
			BlogEntryListGui.getInstance().reloadData();
			SysRuntime.guiManager.back();
		}
	}
	
	private boolean checkOk()
	{
		boolean returnValue;
		String num = numSize.getString();
		if ( num==null || num.length()==0 )
		{
			returnValue = false;
		}
		else
		{
			try
			{
				int n = Integer.parseInt(num);
				if ( publishOk )
				{
					returnValue = (n>=5) && (n<=60);
				}
				else
				{
					returnValue = (n>=5) && (n<=20);
				}
			}
			catch( NumberFormatException e )
			{
				returnValue = false;
			}
		}
		if ( !returnValue )
		{
			Alert alert;
			alert = new Alert( ConstString.GUI_TITLE_PROMPT, StringUtils.combin(ConstString.PROMPT_NUM_SIZE_INVALID, (publishOk)?"60":"20"), null, AlertType.WARNING );
			SysRuntime.guiManager.showAlert(alert, true);
		}
		return returnValue;
	}
}